﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using PuppeteerSharp;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Util.Setvices.Controllers
{
    public class PostRequest
    {
        public List<string> urls { get; set; }
        public string fileName { get; set; }
    }


    public class html2PdfRequest
    {
        /// <summary>
        /// 地址
        /// </summary>
        public string url { get; set; }
        public string fileName { get; set; }

    }

    public class ZipPdfRequest
    {
        public string fileName { get; set; }
        public List<html2PdfRequest> list { get; set; }
    }

    [Route("[controller]")]
    public class FilesController : Controller
    {
        [HttpPost]
        [Route("zipdown")]
        public async Task<IActionResult> OnPostDown([FromBody] PostRequest request)
        {
            if (request == null || request.urls == null || request.urls.Count == 0)
            {
                throw new Exception("缺少参数");
            }

            var fileName = request.fileName ?? "file.zip";
            //先判断是否保存有上次的下载压缩文件
            if (System.IO.File.Exists(Directory.GetCurrentDirectory() + "/wwwroot/" + fileName))
            {
                System.IO.File.Delete(Directory.GetCurrentDirectory() + "/wwwroot/" + fileName);
            }
            var pathZip = Directory.GetCurrentDirectory() + "/wwwroot/downfile/";
            //创建目录的文件路径

            //先根据资料创建文件目录，在循环添加文件在目录下
            var listData = request.urls;
            foreach (var item in listData)
            {

                if (string.IsNullOrEmpty(item.ToString()))
                {
                    continue;
                }
                HttpClient client = new HttpClient();
                //根据文件信息中的文件地址获取远程服务器，返回文件流
                var path = item.ToString();
                var stream = await client.GetStreamAsync(path);
                string filename = System.IO.Path.GetFileName(path);//文件名 “Default.aspx”
                var newPath = pathZip + filename;
                if (!Directory.Exists(pathZip))
                {
                    Directory.CreateDirectory(pathZip);
                }

                var fils = File(stream, "application/vnd.android.package-archive", Path.GetFileName(path));
                //创建文件流(文件路径，文件操作.创建)
                using (FileStream fs = new FileStream(newPath, FileMode.Create))
                {
                    //复制文件流
                    fils.FileStream.CopyTo(fs);
                }
            }
            ZipFile.CreateFromDirectory(Directory.GetCurrentDirectory() + "/wwwroot/downfile/", Directory.GetCurrentDirectory() + "/wwwroot/" + fileName);
            //删除目录以及目录下的子文件
            //存在即删除
            if (Directory.Exists(pathZip))
            {
                Directory.Delete(pathZip, true);
            }

            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            return File("~/" + fileName, "application/octet-stream;charset=UTF-8", fileName);
            //返回压缩文件的路径
            //return Json(new { hrefs = Url.Content("~/file.zip") });
        }

        [HttpPost]
        [Route("zipdown/portrait")]
        public async Task<IActionResult> downZipForPortrait([FromBody] ZipPdfRequest request)
        {
            if (request == null || request.list == null || request.list.Count == 0)
            {
                throw new Exception("缺少参数");
            }

            var fileName = request.fileName ?? "file.zip";
            //先判断是否保存有上次的下载压缩文件
            if (System.IO.File.Exists(Directory.GetCurrentDirectory() + "/wwwroot/" + fileName))
            {
                System.IO.File.Delete(Directory.GetCurrentDirectory() + "/wwwroot/" + fileName);
            }
            var pathZip = Directory.GetCurrentDirectory() + "/wwwroot/downfile/";

            //创建目录的文件路径

            if (!Directory.Exists(pathZip))
            {
                Directory.CreateDirectory(pathZip);
            }

            //先根据资料创建文件目录，在循环添加文件在目录下
            var listData = request.list;

            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
            var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless = true,
                Args = new string[] { "--no-sandbox" }
            });
            var page = await browser.NewPageAsync();
            foreach (var item in listData)
            {

                var url = item.url;
                if (string.IsNullOrEmpty(url))
                {
                    throw new Exception("缺少转换的地址");
                }
                var fileName1 = item.fileName;
                if (string.IsNullOrEmpty(fileName1))
                {
                    fileName1 = $"{Guid.NewGuid().ToString()}.pdf";

                }

                await page.GoToAsync(System.Web.HttpUtility.UrlDecode(url), WaitUntilNavigation.Networkidle0);


                var pdfsteam = await page.PdfStreamAsync(new PdfOptions()
                {
                    PrintBackground = true,
                    Format = PuppeteerSharp.Media.PaperFormat.A4,

                });

                var newPath = pathZip + fileName1;
                //var fils =  File(pdfBytes, "application/octet-stream;charset=UTF-8", $"{fileName1}");

                var fils = File(pdfsteam, "application/vnd.android.package-archive", $"{fileName1}");


                //创建文件流(文件路径，文件操作.创建)
                using (FileStream fs = new FileStream(newPath, FileMode.Create))
                {
                    //复制文件流
                    fils.FileStream.CopyTo(fs);
                }
            }

            await browser.DisposeAsync();
            await page.DisposeAsync();

            ZipFile.CreateFromDirectory(Directory.GetCurrentDirectory() + "/wwwroot/downfile/", Directory.GetCurrentDirectory() + "/wwwroot/" + fileName);
            //删除目录以及目录下的子文件
            //存在即删除
            if (Directory.Exists(pathZip))
            {
                Directory.Delete(pathZip, true);
            }

            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            return File("~/" + fileName, "application/octet-stream;charset=UTF-8", fileName);
            //返回压缩文件的路径
            //return Json(new { hrefs = Url.Content("~/file.zip") });
        }

    }
}
